<?php

use Core\ResourceController;
use Models\Product;
use Models\Favorite;
use Models\User;

class FavoriteController extends ResourceController
{
	public function add_product($id = null)
	{
		if (!$id) {
			return $this->validateError('缺少id');
		}

		$product = (new Product)->find($id);
		if (!$product) {
			return $this->notFoundResponse();
		}

		$favorite = new Favorite;
		$has = $favorite->where(['product_id' => $id, 'user_id' => $this->session->authUser['id']])->get_one();
		if (!$has) {
			$favorite->load([
				'product_id' => $id,
				'user_id' => $this->session->authUser['id'],
				'create_time' => date('Y-m-d H:i:s')
			]);
			$favorite->add();

			return $this->success();
		}

		return $this->validateError('已存在收藏夹');
	}

	public function mulite_add()
	{
		$product_ids = $this->input->post('product_ids');

		foreach ($product_ids as $key => $value) {
			if (!$value) {
				continue;
			}
			$favorite = new Favorite;
			$has = $favorite->where(['product_id' => $value, 'user_id' => $this->session->authUser['id']])->get_one();
			if (!$has) {
				$favorite->load([
					'product_id' => $value,
					'user_id' => $this->session->authUser['id'],
					'create_time' => date('Y-m-d H:i:s')
				]);
				$favorite->add();
			}
		}

		return $this->success();
	}

	public function remove_product($id = null)
	{
		if (!$id) {
			$id = $this->input->post('ids');
		}
		if (!$id) {
			return $this->validateError('缺少id');
		}

		$favorite = new Favorite;
		if (is_array($id)) {
			$favorite->where_in('product_id', $id);
		} else {
			$favorite->where('product_id', $id);
		}

		$favorite->where(['user_id' => $this->session->authUser['id']])->deleteAll();

		return $this->success();
	}

	public function index()
	{
		$favorite = new Favorite;

		$pages = $favorite->where(['user_id' => $this->session->authUser['id']])
			->with(['product'])
			->paginate(20)
			->to_array();

		return $this->success($pages);
	}
}